import React from 'react';
import {Card, Table, Pagination, Divider, ResponsiveGrid, Button, Box, Form, Input, Select, Icon, Radio, Upload, Loading,Dialog,Message, } from '@alifd/next';
import styles from './index.module.scss';
import {listPage, publish, downShelf, deleteVersion} from '@/api/VersionAPI'
import AddVersion from '../AddVersion/AddVersion'
import UpdateVersion from '../UpdateVersion/UpdateVersion'
import DetailVersion from '../DetailVersion/DetailVersion'
import {bToM} from '@/utils/tool'

const { Cell } = ResponsiveGrid;
const { Option } = Select;
const FormItem = Form.Item;

// 是否强制更新
const versionFlagData = [
  {value: "0", label:"非强制"},
  {value: "1", label:"强制"}
];
// 系统类型，2:IOS，3:安卓(暂时定义连个系统)
const osTypeData = [
  // {value: "0", label:"--"},
  // {value: "1", label:"--"},
  {value: "2", label:"IOS"},
  {value: "3", label:"安卓"}
];
// 状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
const statesData = [
  {value:'0', label:"未发布"},
  {value:'1', label:"停用"},
  {value:'2', label:"已发布"},
  {value:'3', label:"已下架"}
];

const DEFAULT_DATA = {
  records: [],
  // 查询参数
  QueryParam: {
    page:{
      current: 1,
      size: 10
    },
    query: "",
    releaseState: null,
    osType: null,
    versionFlag:null,
  },
  total: 0,
};

/**
 * 版本列表
 * 日期：2020-07-04
 */
class VersionList extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
        dataSource: DEFAULT_DATA,
        loading: true,
        courseOptionList: [],
        courseBaseOption: [],
        examPaperOptionList:[],
    };

  }
  // 初始化方法
  componentDidMount(){
    this.onOperation();
  };
  // 加载列表动作
  onOperation = () => {
      // 1.1 调用 VersionAPI listPage 接口
      listPage(DEFAULT_DATA.QueryParam).then((data)=>{
        if(data){
          const list = data.records;
          // 处理状态、类型
          if(list){
            for (const i in list) {
              const v = list[i]
              // 处理状态
              for(const j in statesData){
                const s = statesData[j]
                let st = '' + v.releaseState;
                if(st == s.value){
                  v.releaseStateV = s.label
                }
              }
              // 处理是否强制更新
              for(const z in versionFlagData){
                const t = versionFlagData[z]
                let tv = '' + v.versionFlag;
                if(tv == t.value){
                  v.versionFlagV = t.label
                }
              }
              let appSizeV = bToM(v.appSize)
              v.appSizeV  = appSizeV
            }
          }
          DEFAULT_DATA.total = data.total;
          DEFAULT_DATA.records = list;
          this.setState({ 
            DEFAULT_DATA,
            loading: false,
          }) 
        }
      });
  };

  // 动态变更 模糊条件
  changeQuery = (e) => {
    DEFAULT_DATA.QueryParam.query = e
  };
  // 动态变更 状态
  changeState = (e) => {
    DEFAULT_DATA.QueryParam.releaseState = e
  };
  // 动态变更 系统类型
  changeOsType = (e) => {
    DEFAULT_DATA.QueryParam.osType = e
  };
  // 动态变更 强制更新属性
  changeVersionFlag = (e) => {
    DEFAULT_DATA.QueryParam.versionFlag = e
  };

  // 重置
  onReset = (v) => {
    DEFAULT_DATA.QueryParam.osType = null
    DEFAULT_DATA.QueryParam.releaseState = null
    DEFAULT_DATA.QueryParam.query = null
    DEFAULT_DATA.QueryParam.versionFlag = null
    this.state = {
      DEFAULT_DATA,
      queryValue:'',
    };
  };

  // 下架事件
  downShelfButton = (v) => {
    Dialog.confirm({
      title: '是否下架',
      onOk: () => {
        downShelf(v).then((flag)=>{
          if(flag){
            Message.success('下架成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 发布事件
  publishButton = (v) => {
    Dialog.confirm({
      title: '是否发布',
      onOk: () => {
        publish(v).then((flag)=>{
          if(flag){
            Message.success('发布成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 删除
  delButton = (v) => {
    Dialog.confirm({
      title: '是否确定要删除',
      onOk: () => {
        deleteVersion(v).then((flag)=>{
          if(flag){
            Message.success('删除成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 分页查询：
  onPaginationChange = (e) => {
    DEFAULT_DATA.QueryParam.page.current = e 
    this.state = {
      DEFAULT_DATA
    };
    this.onOperation();
  };
  // 点击查询
  onFindCourse = () =>{
    DEFAULT_DATA.QueryParam.page.current = 1
    this.state = {
      DEFAULT_DATA
    };
    this.onOperation();
  };

  handlerOperatorButton = (value, index, model) =>{
      // 试卷-试题状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
      if(model.releaseState == 0 || model.releaseState == 3){
        return (
          <div className={styles.opt}>
            <Button type="primary" text  onClick={()=>this.openUpdateVersion(model.id)}>编辑</Button>
            <Button type="primary" text style={{color: 'green'}} onClick={()=> this.publishButton(model.id) }>发布</Button>
            <Button type="primary" text style={{color: 'red'}} onClick={()=> this.delButton(model.id)}>删除</Button>
          </div>
        )
      }else if(model.releaseState == 2){
        return (
          <div className={styles.opt}>
            <Button type="primary" text style={{color: 'black'}} onClick={()=> this.downShelfButton(model.id)}>下架</Button>
          </div>
        )
      }else if(model.releaseState == 1){
        return (
          <div className={styles.opt}>
            <Button type="primary" text style={{color: 'red'}} onClick={()=> this.delButton(model.id)}>删除</Button>
          </div>
        )
      }
  };
  // 打开新增页面
  openAddVersion = () =>{
    this.AddVersion.onOpen(statesData, osTypeData, versionFlagData) 
  };
  // 新增组件引用
  onRefAddVersion = (ref) => {
    this.AddVersion = ref
  }
  // 打开修改页面
  openUpdateVersion = (key) =>{
      this.UpdateVersion.onOpen(key, statesData, osTypeData, versionFlagData) 
  };
  // 修改组件引用
  onRefUpdateVersion = (ref) => {
    this.UpdateVersion = ref
  }

  // 打开详情页面
  openDetailVersion = (key) =>{
      this.DetailVersion.onOpen(key, statesData, osTypeData, versionFlagData) 
  };
  // 修改组件引用
  onRefDetailVersion = (ref) => {
    this.DetailVersion = ref
  }

  // 新增或修改 回调刷新列表
  onFreshList = () => {
    this.onOperation();
  }

  render(){
    return (
      <>
        <Card free>
          <Card.Content>
            <Box padding={10}>
              <Form responsive fullWidth labelAlign="top">
                <FormItem  colSpan={2} label="模糊条件">
                  <Input name='query' onChange={this.changeQuery} placeholder="支持名称、代码、版本号" hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="状态">
                  <Select name='releaseState' placeholder="选择状态" dataSource= {statesData || []} onChange={this.changeState} hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="类型">
                  <Select name='osType' placeholder="系统类型" dataSource= {osTypeData || []} onChange={this.changeOsType} hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="是否强制">
                  <Select name='versionFlag' placeholder="是否强制更新" dataSource= {versionFlagData || []} onChange={this.changeVersionFlag} hasClear/>
                </FormItem>
                <Cell colSpan={3} className={styles.btns}>
                  <Box spacing={8} direction="row" align="flex-end" justify="center" style={{height: '100%',}}>
                    <Button type="primary" onClick={this.onFindCourse}>查询</Button>
                    <Form.Reset onClick={this.onReset} names={['query','releaseState','osType','versionFlag']}>重置</Form.Reset>
                  </Box>
                </Cell>
              </Form>
            </Box>
            <Divider dashed />
            <div className={styles.Main}>
              <Loading visible={this.state.loading}>
                <div className={styles.add}>
                  <AddVersion onRef={this.onRefAddVersion} onFreshList = {this.onFreshList}/>
                  <UpdateVersion onRef={this.onRefUpdateVersion} onFreshList = {this.onFreshList}/>
                  <DetailVersion onRef={this.onRefDetailVersion} />
                  <Button type="primary" onClick={this.openAddVersion}>新增试题</Button>
                </div>
                <Table
                  hasBorder={false}
                  className={styles.Table}
                  dataSource={this.state.dataSource.records}
                  rowSelection={{
                    columnProps: () => ({
                      lock: 'left',
                    }),
                  }}
                >
                  <Table.Column title="标识" dataIndex="id" key='id' width={75}
                    cell = {(key) =>(<a onClick={()=>this.openDetailVersion(key)}>
                      <span style={{ color: "blue", cursor: "pointer"}}>{key}</span>
                      </a>)}
                  />
                  <Table.Column title="名称" dataIndex="name" key='name' width={200}/>
                  <Table.Column title="代码" dataIndex="code" key='code' width={150}/>
                  <Table.Column title="版本号" dataIndex="versionNum" key='versionNum' width={150}/>
                  <Table.Column title="版本代码" dataIndex="versionCode" key='versionCode' width={100}/>
                  <Table.Column title="大小" dataIndex="appSizeV" key='appSize' width={150}/>
                  <Table.Column title="强制更新" dataIndex="versionFlagV" key='versionFlag' width={150}/>
                  <Table.Column title="系统类型" dataIndex="osName" key='osName' width={150}/>
                  <Table.Column title="状态" dataIndex="releaseStateV" key='releaseStateV' width={100}/>
                  <Table.Column title="发布时间" dataIndex="releaseTime" key='releaseTime' width={140}/>
                  {/* <Table.Column title="创建时间" dataIndex="createTime" key='createTime' width={200}/> */}
                  <Table.Column title="操作" cell={this.handlerOperatorButton} />
                </Table>
                <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                  <div className={styles.total}>
                    每页<span>{this.state.dataSource.QueryParam.page.size}</span>条，共<span>{this.state.dataSource.total}</span>条
                  </div>
                  <Pagination pageSize={this.state.dataSource.QueryParam.page.size} total={this.state.dataSource.total} onChange={this.onPaginationChange} />
                </Box>
              </Loading>
            </div>
          </Card.Content>
        </Card>
      </>
    );
  };
}

export default VersionList;